package com.nic.view.util.glide;


import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Looper;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.cache.ExternalCacheDiskCacheFactory;
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;
import com.bumptech.glide.request.target.Target;
import com.nic.view.ViewConfig;
import com.nic.view.util.JLog;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.math.BigDecimal;

import jp.wasabeef.glide.transformations.RoundedCornersTransformation;

/**
 * Glide乱序时所关联的imageView setTag(resId,str)
 * <p>
 * Created by Administrator on 2018/10/24.
 */

public class GlideUtil {
    private static GlideUtil mGlideUtil;

    public static GlideUtil getInstance() {
        if (mGlideUtil == null) {
            synchronized (GlideUtil.class) {
                mGlideUtil = new GlideUtil();
            }
        }
        return mGlideUtil;
    }

    public void load(String url, ImageView imageView) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        load(ViewConfig.applicationContext, url, imageView, null);
    }
    public void loadSmallRadius(String url, ImageView imageView) {
        loadSmallRadius(ViewConfig.applicationContext, url, imageView, null);
    }
    public void loadSmall(String url, ImageView imageView) {
        Glide.with(ViewConfig.applicationContext).load(url).diskCacheStrategy(DiskCacheStrategy.NONE).override(320, 320).centerCrop().into(
                imageView);
    }
    public void loadSmall(Bitmap bmp, ImageView imageView) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] bytes = baos.toByteArray();
        int dp4 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, ViewConfig.applicationContext.getResources().getDisplayMetrics());
        Glide.with(ViewConfig.applicationContext).load(bytes)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .override(96, 96).centerCrop()
                .dontAnimate()
                .bitmapTransform(new RoundedCornersTransformation(ViewConfig.applicationContext, dp4, 0)).into(
                imageView);
    }
    public void load(byte[] bytes, ImageView imageView) {

        Glide.with(ViewConfig.applicationContext).load(bytes).diskCacheStrategy(DiskCacheStrategy.NONE).into(imageView);
    }

    public void load(Bitmap bitmap, ImageView imageView) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] bytes = baos.toByteArray();
        load(bytes, imageView);
    }

    public void load(int resId, ImageView imageView) {
        Glide.with(ViewConfig.applicationContext).load(resId).diskCacheStrategy(DiskCacheStrategy.NONE).dontAnimate().into(imageView);
    }

    public void loadGif(byte[] bytes, ImageView imageView) {
        //.diskCacheStrategy(DiskCacheStrategy.SOURCE)
        Glide.with(ViewConfig.applicationContext).load(bytes).asGif().diskCacheStrategy(DiskCacheStrategy.NONE).into(imageView);
    }

    public void loadAssets(String fileName, ImageView imageView) {
        //.diskCacheStrategy(DiskCacheStrategy.SOURCE)
        Glide.with(ViewConfig.applicationContext).load("file:///android_asset/" + fileName).diskCacheStrategy(DiskCacheStrategy.NONE).dontAnimate().into(imageView);
    }

    public void loadGif(String path, ImageView imageView) {
        //.diskCacheStrategy(DiskCacheStrategy.SOURCE)
        if (!path.equals(imageView.getTag())) {
            imageView.setTag(path);
        }
        Glide.with(ViewConfig.applicationContext).load(path).asGif().diskCacheStrategy(DiskCacheStrategy.NONE).into(imageView);
    }

    public void load(String url, ImageView imageView, OnImageResultListener onLoadComplete) {
        load(ViewConfig.applicationContext, url, imageView, onLoadComplete);
    }

    public void loadAvatar(String url, ImageView imageView) {
        Glide.with(ViewConfig.applicationContext)
                .load(url)
                .placeholder(ViewConfig.LOADING_IMG_ID) //加载中
                .error(ViewConfig.LOADING_ERROR_ID)//加载失败
                .fallback(ViewConfig.LOADING_IMG_ID)//加载为空
                .priority(Priority.HIGH)//加载的优先等级
                .diskCacheStrategy(DiskCacheStrategy.NONE)//缓存类型
//                .bitmapTransform(new CropCircleTransformation(ChatApp.getInstance()))
                .bitmapTransform(new RoundedCornersTransformation(ViewConfig.applicationContext, 6, 0))
                .into(imageView);
    }

    public <T> void load(T t, String url, ImageView imageView) {
        load(t, url, imageView, null);
    }

    /**
     * @param t
     * @param url            网络地址或本地路径
     * @param imageView
     * @param onLoadComplete
     * @param <T>
     */
    public <T> void load(T t, String url, ImageView imageView, final OnImageResultListener onLoadComplete) {
        int dp4 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, ViewConfig.applicationContext.getResources().getDisplayMetrics());
        load(t, url, imageView, onLoadComplete, dp4);
    }
    public <T> void loadSmallRadius(T t, String url, ImageView imageView, final OnImageResultListener onLoadComplete) {
        int dp4 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, ViewConfig.applicationContext.getResources().getDisplayMetrics());
        load(t, url, imageView, onLoadComplete, dp4);
    }
    public <T> void load(T t, String url, ImageView imageView, final OnImageResultListener onLoadComplete, int radius) {
//        if (!url.equals(imageView.getTag())) {
        if (TextUtils.isEmpty(url)) {
            if (onLoadComplete != null) {
                onLoadComplete.onLoadComplete();
            }
            return;
        }
        RequestManager manager;
        if (t instanceof Activity) {
            manager = Glide.with((Activity) t);
        } else if (t instanceof Fragment) {
            manager = Glide.with((Fragment) t);
        } else if (t instanceof Context) {
            manager = Glide.with((Context) t);
        } else {
            manager = Glide.with(ViewConfig.applicationContext);
        }
        if (url.startsWith("http")) {
            manager.load(url).placeholder(ViewConfig.LOADING_IMG_ID).error(ViewConfig.LOADING_ERROR_ID).into(new GlideDrawableImageViewTarget(imageView) {
                @Override
                public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> animation) {
                    super.onResourceReady(resource, animation);
                    if (onLoadComplete != null) {
                        onLoadComplete.onLoadComplete();
                    }
                }

                @Override
                public void onLoadFailed(Exception e, Drawable errorDrawable) {
                    super.onLoadFailed(e, errorDrawable);
                    if (onLoadComplete != null) {
                        onLoadComplete.onLoadError();
                        onLoadComplete.onLoadComplete();
                    }
                }
            });
        } else {

            Uri uri = null;
            if (!url.contains("file:///android_asset")) {
                File file = new File(url);
                if (!file.exists()) {
                    if (onLoadComplete != null) {
                        onLoadComplete.onLoadError();
                        onLoadComplete.onLoadComplete();
                    }
                    return;
                }
                uri = Uri.fromFile(file);
            }
            manager.load(uri != null ? uri : url)
                    .placeholder(imageView.getDrawable())
                    .error(ViewConfig.LOADING_ERROR_ID)//加载失败
                    .fallback(ViewConfig.LOADING_ERROR_ID)//加载为空
                    .priority(Priority.NORMAL)//加载的优先等级
                    .diskCacheStrategy(DiskCacheStrategy.NONE)//缓存类型
                    .skipMemoryCache(false)
                    .dontAnimate()
                    .bitmapTransform(new RoundedCornersTransformation(ViewConfig.applicationContext, radius, 0))
                    .into(new GlideDrawableImageViewTarget(imageView) {
                        @Override
                        public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> animation) {
                            super.onResourceReady(resource, animation);
                            if (onLoadComplete != null) {
                                onLoadComplete.onLoadComplete();
                            }
                        }

                        @Override
                        public void onLoadFailed(Exception e, Drawable errorDrawable) {
                            super.onLoadFailed(e, errorDrawable);
                            if (onLoadComplete != null) {
                                onLoadComplete.onLoadError();
                                onLoadComplete.onLoadComplete();
                            }
                        }
                    });
        }
//            imageView.setTag(url);
//        }
    }

    public void loadImage(String url, OnImageResultListener onImageResultListener) {
//        url = "http://192.168.0.104:8888/group1/M00/00/30/wKgAaFvJMgWAPxauAASNQROcqp8315.png";
        new getImageCacheAsyncTask(onImageResultListener).execute(url);
    }


    private class getImageCacheAsyncTask extends AsyncTask<String, Void, File> {
        private OnImageResultListener onImageResultListener;

        public getImageCacheAsyncTask(OnImageResultListener onImageResultListener) {
            this.onImageResultListener = onImageResultListener;
        }

        @Override

        protected File doInBackground(String... params) {
            if (params == null || params.length < 1 || TextUtils.isEmpty(params[0])) {
                return null;
            }
            String imgUrl = params[0];
            try {
                // Glide v3
                return Glide
                        .with(ViewConfig.applicationContext)
                        .load(imgUrl)
                        .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                        .get(); // needs to be called on background thread

            } catch (Exception ex) {
                Log.w("SHARE", "Sharing " + imgUrl + " failed", ex);
                return null;
            }
        }

        @Override
        protected void onPostExecute(File result) {
            //此path就是对应文件的缓存路径
            if (result == null || TextUtils.isEmpty(result.getPath())) {
                if (onImageResultListener != null) {
                    onImageResultListener.onLoadError();
                }
            } else {
                JLog.d("load image path->" + result.getPath());
                if (onImageResultListener != null) {
                    onImageResultListener.onLoadSuccess(result.getPath());
                }
            }
            if (onImageResultListener != null) {
                onImageResultListener.onLoadComplete();
            }
        }

    }

    public interface OnImageResultListener {
        void onLoadSuccess(String path);

        void onLoadError();

        void onLoadComplete();
    }

    /**
     * 清除图片磁盘缓存
     */
    public void clearImageDiskCache(final Context context) {
        try {
            if (Looper.myLooper() == Looper.getMainLooper()) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Glide.get(context).clearDiskCache();
// BusUtil.getBus().post(new GlideCacheClearSuccessEvent());
                    }
                }).start();
            } else {
                Glide.get(context).clearDiskCache();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 清除图片内存缓存
     */
    public void clearImageMemoryCache(Context context) {
        try {
            if (Looper.myLooper() == Looper.getMainLooper()) { //只能在主线程执行
                Glide.get(context).clearMemory();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 清除图片所有缓存
     */
    public void clear(ImageView imageView) {
        Glide.clear(imageView);
    }

    /**
     * 清除图片所有缓存
     */
    public void clearImageAllCache(Context context) {
        clearImageDiskCache(context);
        clearImageMemoryCache(context);
        String ImageExternalCatchDir = context.getExternalCacheDir() + ExternalCacheDiskCacheFactory.DEFAULT_DISK_CACHE_DIR;
        deleteFolderFile(ImageExternalCatchDir, true);
    }

    /**
     * 获取Glide造成的缓存大小
     *
     * @return CacheSize
     */
    public String getCacheSize(Context context) {
        try {
            return getFormatSize(getFolderSize(new File(context.getCacheDir() + "/" + InternalCacheDiskCacheFactory.DEFAULT_DISK_CACHE_DIR)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取指定文件夹内所有文件大小的和
     *
     * @param file file
     * @return size
     * @throws Exception
     */
    private long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (File aFileList : fileList) {
                if (aFileList.isDirectory()) {
                    size = size + getFolderSize(aFileList);
                } else {
                    size = size + aFileList.length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    /**
     * 删除指定目录下的文件，这里用于缓存的删除
     *
     * @param filePath       filePath
     * @param deleteThisPath deleteThisPath
     */
    private void deleteFolderFile(String filePath, boolean deleteThisPath) {
        if (!TextUtils.isEmpty(filePath)) {
            try {
                File file = new File(filePath);
                if (file.isDirectory()) {
                    File files[] = file.listFiles();
                    for (File file1 : files) {
                        deleteFolderFile(file1.getAbsolutePath(), true);
                    }
                }
                if (deleteThisPath) {
                    if (!file.isDirectory()) {
                        file.delete();
                    } else {
                        if (file.listFiles().length == 0) {
                            file.delete();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 格式化单位
     *
     * @param size size
     * @return size
     */
    private static String getFormatSize(double size) {

        double kiloByte = size / 1024;
        if (kiloByte < 1) {
            return size + "Byte";
        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);

        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
    }

}
